<script setup>
import newLoading from '@/components/newLoading/index.vue';
import tgpTextarea from './child/tgpTextarea.vue'
import Toast from '@vant/weapp/dist/toast/toast';
import { getCategoryDetail } from "@/api/home";
import { editImgUpload, createImage, getImageByTaskId } from "@/api/painting";
import { usePaintingStore } from "@/store";
import { ref, nextTick, computed } from 'vue'
import { onLoad, onUnload } from '@dcloudio/uni-app'


const paintingStore = usePaintingStore()


// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 查询参数
const queryParams = ref({
  style: '通用', // 绘图风格
  refMode: 'refonly', // 参考方式
  refStrength: 0.5, // 参考程度
  refImgUrl: '', // 背景参考图地址
  num: 1, // 图片数量
  size: '', // 画布比例
  model: 'DOUBAO',
  modelVersion: 'V2',
  imgModel: 'general_v20_9B_pe'

})
// 提交数据
const queryData = ref({})
// 消耗算力
const expendNum = ref(0)


// 模型列表
const modelList = ref([])
// 图片数量列表
const imgNumList = ref([])
// 风格数组
const styleList = ref([
  { label: "通用" },
  { label: "动画" },
  { label: "3D卡通" },
  { label: "素描" },
  { label: "中国画", },
  { label: "油画", },
  { label: "水彩", },
  { label: "扁平插画", },
])
// 完整画布比例列表
const oldSizeList = ref([
  {
    id: 1,
    iconfont: "ai-icon-a-1_1",
    content: "1:1",
    value: "1024x1024",
    imgModel: "TY-e-1",
  },
  {
    id: 2,
    iconfont: "ai-icon-a-3_4",
    content: "9:16",
    value: "720x1280",
    imgModel: "TY-e-1",
  },
  {
    id: 3,
    iconfont: "ai-icon-a-4_3",
    content: "16:9",
    value: "1280x720",
    imgModel: "TY-e-1",
  },
  {
    id: 4,
    iconfont: "ai-icon-a-3_4",
    content: "3:4",
    value: "1280x720",
    imgModel: "TY-e-1",
  },
  {
    id: 5,
    iconfont: "ai-icon-a-4_3",
    content: "4:3",
    value: "1280x720",
    imgModel: "TY-e-1",
  },
])
// 画布比例数组
const sizeList = ref([...oldSizeList.value])

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null
// 文本域ref
const tgpareaRef = ref(null)

const placeholder = computed(() => {
  if (queryParams.value.modelVersion === 'V2') {
    return '4K HDR超清视界，AI智能生成中英双语海报，极速渲染，震撼视效一键呈现'
  } else {
    return '极具想象力，擅长写真摄影'
  }
})


// 开始生成
async function startFn() {
  clearInterval(timer);
  queryData.value.prompt = tgpareaRef.value.getPromptInfo().prompt
  tgpareaRef.value.setLocalSelectList()
  if (!queryData.value.prompt) return Toast.fail('请输入描述词')
  loading.value = true
  // if (queryParams.value.refImgUrl && queryParams.value.modelVersion === 'V3') {
  //   await editImgUploadFn()
  // }
  createImageFn()
}



// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    const data = {
      id: res.data.id,
      title: queryInfo.value.title,
      modelTypeId: queryItem.value.modelTypeId,
    }
    uni.navigateTo({
      url: `/draw/paintingResultPage/index?item=${JSON.stringify(data)}`,
    });

  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1]
    Toast.fail(errorMessage);
    loading.value = false
  }
}


// 文生图任务提交
async function createImageFn() {
  try {
    queryData.value = Object.assign(queryParams.value, queryData.value)
    if (queryParams.value.modelVersion !== 'V3') {
      queryData.value.refImgUrl = ''
    }
    const res = await createImage(queryData.value)
    paintingStore.setTextCreateImageFn(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }
}


// 上传背景参考原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 1,
        orgImg: queryParams.value.refImgUrl
      })
      queryData.value.refImgUrl = res
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}



// 风格点击事件
function styleItemClick(e) {
  queryParams.value.style = e.label
}


// 参考方式点击事件
function refModeItemClick(e) {
  queryParams.value.refMode = e
}


// 清除背景参考图
function clearImgFn() {
  queryParams.value.refImgUrl = ''
}


// 上传背景参考图
function uploadImgFn() {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      queryParams.value.refImgUrl = res.tempFilePaths[0]
    },
  });
}

// 模型点击事件
function modelItemClick(e) {
  queryParams.value.modelVersion = e.modelVersion
  // if (e.modelVersion === 'V3') {
  //   queryParams.value.model = 'TYWX'
  //   queryParams.value.imgModel = 'TY-e-1'
  //   sizeList.value = oldSizeList.value.slice(0, 3)
  // } else {
  queryParams.value.model = 'DOUBAO'
  queryParams.value.imgModel = 'general_v20_9B_pe'
  sizeList.value = [...oldSizeList.value]
  // }
  queryParams.value.size = sizeList.value[0].content
}

// 生成数量点击事件
function imgNumClick(e) {
  queryParams.value.num = e
}

// 画布比例点击事件
function sizeItemClick(e) {
  queryParams.value.size = e.content
}



// 获取模型列表
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id);
  queryInfo.value = res.data

  res.data.categoryParam.forEach(item => {
    if (item.title === 'model') {
      modelList.value = item.data
      modelList.value.forEach(item => {
        item.label = item.title.split('-')[1]
        item.modelVersion = item.title.split('-')[0]
      })
      queryParams.value.modelVersion = modelList.value[0].modelVersion
    } else if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    } else if (item.title === 'imgNum') {
      imgNumList.value = item.data[0].title.split(',')
      queryParams.value.num = imgNumList.value[0]
    }
  })
};

// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}


// 格式化页面传递查询数据
function formatQueryData() {
  if (queryItem.value.imageFileUrl) {
    uni.getImageInfo({
      src: queryItem.value.imageFileUrl,
      success(res) {
        queryParams.value.refImgUrl = res.path
      }
    })
  }
  if (queryItem.value.prompt) {
    nextTick(() => {
      tgpareaRef.value.setPrompt(queryItem.value.prompt)
    })
  }
}

onUnload(() => {
  clearInterval(timer);
  loading.value = false
})

onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
    formatQueryData()
  }
  queryParams.value.size = sizeList.value[0].content
  getCategoryDetailFn()
})


</script>

<template>
  <div class='textGeneratePic'>
    <NavBar>{{ queryInfo?.title }}</NavBar>
    <div class="container">
      <div class="title_box">模型</div>
      <div class="modal_list">
        <div class="modal_item" :class="{ active: queryParams.modelVersion === item.modelVersion }"
          v-for="item of modelList" @click="modelItemClick(item)">
          {{ item.label }}
        </div>
      </div>
      <tgpTextarea ref="tgpareaRef" :placeholder="placeholder"></tgpTextarea>

      <!-- <div v-if="queryParams.modelVersion === 'V3'">
        <div class="title_box">风格</div>
        <div class="style_list">
          <div class="style_item" :class="{ active: queryParams.style === item.label }" v-for="item of styleList"
            @click="styleItemClick(item)">
            <img :src="`https://www.topyunliu.com/imgs/paint/style/${item.label}.png`" class="style_img"
              mode="aspectFill" />
            <div class="style_text">{{ item.label }}</div>
          </div>
        </div>
      </div> -->


      <!-- <div v-if="queryParams.modelVersion === 'V3'">
        <div class="title_box">
          背景参考图
          <div class="text">（AI会在参考图基础上，进行绘制）</div>
        </div>
        <div class="upload_box" @click="uploadImgFn">
          <image :src="queryParams.refImgUrl" v-if="queryParams.refImgUrl" mode="aspectFit" />
          <i class="iconfont ai-icon-jia" v-else></i>
          <div class="clear_icon_box" v-if="queryParams.refImgUrl" @click.stop="clearImgFn">
            <div class="clear_icon">
              <i class="iconfont ai-icon-shanchutupian"></i>
            </div>
          </div>
        </div>
        <div class="label_box">
          <div class="label">参考方式</div>
          <div class="value">
            <div class="refMode_list">
              <div class="refMode_item" :class="{ active: queryParams.refMode === 'refonly' }"
                @click="refModeItemClick('refonly')">图片风格</div>
              <div class="refMode_item" :class="{ active: queryParams.refMode === 'repaint' }"
                @click="refModeItemClick('repaint')">图片内容</div>
            </div>
          </div>
        </div>

        <div class="label_box">
          <div class="label">参考程度</div>
          <div class="value">
            <div class="slider_box">
              <van-slider v-model:value="queryParams.refStrength" :max="1" :min="0.1" :step="0.1" use-button-slot
                @drag="(e) => (queryParams.refStrength = e.detail.value)"
                @change="(e) => (queryParams.refStrength = e.detail)" bar-height="4px">
                <template #button>
                  <div class="custom-button">
                    {{ queryParams.refStrength }}
                  </div>
                </template>
              </van-slider>
            </div>
          </div>
        </div>
      </div> -->




      <div class="title_box">画布比例</div>
      <div class="size_list">
        <div class="size_item" :class="{ active: queryParams.size === item.content }" v-for="item of sizeList"
          @click="sizeItemClick(item)">
          <i :class="`iconfont ${item.iconfont}`"></i>
          <div>{{ item.content }}</div>
        </div>
      </div>


      <div class="title_box">生成数量</div>
      <div class="imgNum_list">
        <div class="imgNum_item" :class="{ active: +queryParams.num === +item }" v-for="item of imgNumList"
          @click="imgNumClick(item)">{{ item }}</div>
      </div>

    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <myDrawButton :expendNum="expendNum * queryParams.num" @click="startFn"></myDrawButton>
      </div>
    </div>
  </div>
  <van-toast id="van-toast"></van-toast>
  <newLoading ref="loadingRef" v-model="loading" :duration="15000" :label="['排队中，预计等待20秒']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
::v-deep.van-slider {
  display: block;
  width: 100% !important;
  border-radius: 20rpx !important;
}

::v-deep.van-slider__bar {
  background-color: var(--a-main-color);
}

.custom-button {
  width: 45rpx;
  height: 45rpx;
  line-height: 45rpx;
  border-radius: 50%;
  background-color: var(--a-one-text-color);
  font-size: 20rpx;
  text-align: center;
  color: var(--a-main-color);
}

.textGeneratePic {
  .container {
    padding: 0 30rpx 30rpx;

    .title_box {
      position: relative;
      font-size: 28rpx;
      color: var(--a-one-text-color);
      font-weight: bold;
      padding-left: 30rpx;
      margin: 40rpx 0 18rpx;
      display: flex;
      align-items: center;

      &.spaceBetween {
        justify-content: space-between;
      }

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translate(0, -50%);
        width: 12rpx;
        height: 18rpx;
        background: var(--a-main-color);
        border-radius: 6rpx;
      }

      .text {
        font-size: 24rpx;
      }
    }

    .label_box {
      display: flex;
      align-items: center;
      gap: 45rpx;
      margin-top: 34rpx;

      .label {
        flex-shrink: 0;
        color: var(--a-one-text-color);
        font-size: 26rpx;
      }

      .value {
        flex: 1;

        .refMode_list {
          display: flex;
          align-items: center;
          gap: 16rpx;

          .refMode_item {
            width: 241rpx;
            height: 53rpx;
            font-size: 22rpx;
            color: var(--a-one-text-color);
            border-radius: 12rpx;
            border: 2rpx solid var(--a-main-box-bg-color);
            background-color: transparent;
            display: flex;
            align-items: center;
            justify-content: center;

            &.active {
              color: var(--a-main-color);
              border: 2rpx solid var(--a-main-color);
            }
          }
        }

        .slider_box {
          width: 100%;
        }
      }
    }

    .modal_list {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .modal_item {
        box-sizing: border-box;
        width: 241rpx;
        height: 53rpx;
        font-size: 22rpx;
        color: var(--a-one-text-color);
        border-radius: 12rpx;
        border: 2rpx solid var(--a-main-box-bg-color);
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: var(--a-main-color);
          border: 2rpx solid var(--a-main-color);
        }
      }
    }

    .style_list {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      grid-column-gap: 17rpx;
      grid-row-gap: 26rpx;

      .style_item {
        &.active {
          .style_img {
            border: 4rpx solid var(--a-main-color);
          }

          .style_text {
            color: var(--a-main-color);
          }
        }

        .style_img {
          box-sizing: border-box;
          display: block;
          width: 100%;
          height: 154rpx;
          border-radius: 24rpx;
          border: 4rpx solid transparent;
        }

        .style_text {
          font-size: 26rpx;
          color: var(--a-one-text-color);
          text-align: center;
          margin-top: 12rpx;
        }
      }

    }

    .upload_box {
      position: relative;
      width: 160rpx;
      height: 160rpx;
      border-radius: 24rpx;
      color: var(--a-main-color);
      background: var(--a-main-box-bg-color);
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;

      .iconfont {
        font-size: 32rpx;
      }

      .clear_icon_box {
        position: absolute;
        top: 0;
        right: 0;
        width: 60rpx;
        height: 60rpx;

        .clear_icon {
          position: absolute;
          top: 0;
          right: 0;
          width: 40rpx;
          height: 40rpx;
          border-radius: 0 0 0 24rpx;
          background-color: rgba(0, 0, 0, 0.3);
          display: flex;
          align-items: center;
          justify-content: center;

          .iconfont {
            font-size: 24rpx;
            color: var(--a-one-text-color);
          }
        }
      }
    }

    .size_list {
      display: flex;
      align-items: center;
      gap: 16rpx;
      flex-wrap: wrap;

      .size_item {
        flex-shrink: 0;
        box-sizing: border-box;
        width: 124rpx;
        height: 124rpx;
        color: var(--a-one-text-color);
        border-radius: 13rpx;
        border: 4rpx solid transparent;
        background: var(--a-main-box-bg-color);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        gap: 8rpx;

        .iconfont {
          font-size: 47rpx;
        }

        &.active {
          color: var(--a-main-color) !important;
          border: 4rpx solid var(--a-main-color) !important;
        }
      }


    }

    .imgNum_list {
      display: flex;
      align-items: center;
      gap: 18rpx;

      .imgNum_item {
        box-sizing: border-box;
        width: 84rpx;
        height: 84rpx;
        color: var(--a-one-text-color);
        background: var(--a-main-box-bg-color);
        border-radius: 13rpx;
        border: 4rpx solid transparent;
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: var(--a-main-color) !important;
          border: 4rpx solid var(--a-main-color) !important;
        }
      }
    }
  }

  .footer {
    .footer_placeholder {
      height: 176rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 176rpx;
      background: #212142;
      padding: 28rpx 30rpx 0;
    }
  }
}
</style>